package com.milo.web.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.pattern.PathPatternParser;

import javax.servlet.ServletContext;


/**
 * 系统配置类
 * @author Milo Lee
 * @date 2021-12-04 11:19
 *
 */
//@Configuration
public class SystemConfig implements WebMvcConfigurer {

    @Autowired
    private ServletContext servletContext;

    /**
     * 静态资源地址
     */
    @Value("${web.staticUrl}")
    String webStaticUrl;

	/**
     * 附件上传地址
     */
    @Value("${web.uploadFileUrl}")
    String uploadFileUrl;

    /**
     * 全局地址
     */
    @Value("${web.globalUrl}")
    String globalUrl;



    /**
     * 注入从yml文件获取的配置信息到servletContext 提供给thymeleaf的页面使用
     * html页面中通过：${application.webStaticUrl}获取
     */
    @Bean
    public void setServletContext(){
        servletContext.setAttribute("webStaticUrl",webStaticUrl);
        servletContext.setAttribute("uploadFileUrl",uploadFileUrl);
        servletContext.setAttribute("globalUrl",globalUrl);
    }

    /**
     * 配置跨域
     *
     * @return
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(Boolean.TRUE);
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }

}
